import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ws2812_time/view/config/logic.dart';
import 'package:ws2812_time/view/home/logic.dart';
import 'package:ws2812_time/view/power/logic.dart';

final homelogic = Get.put(HomeLogic());
final powerlogic = Get.put(PowerLogic());
final configlogic = Get.put(ConfigLogic());

class Config {
  static String host = "192.168.";
  static String mac = "";
  static int bright = 0;
  static String color = "0,0,0";
  //   "IP": "192.168.31.87",
  //   "MAC": "48:55:19:7A:9D:1F",
  //   "Bright": 10,
  //   "Timecolor": "135,206,235"
  static RxBool isOK = false.obs;
  static Dio dio = Dio();
  // 保存配置
  static Future saveConfig() async {
    var config = await SharedPreferences.getInstance(); //初始化
    config.setString("host", Config.host);
    config.setString("mac", Config.mac);
    debugPrint("保存配置");
  }

  // 读取配置 todo-- 启动运行
  static Future initConfig() async {
    try {
      //初始化 配置文件
      var config = await SharedPreferences.getInstance();
      debugPrint("读取配置");
      // 读取上次IP
      Config.host = config.getString("host")!;
      // 读取上次MAC
      Config.mac = config.getString("mac")!;
      // 连接WebLED 服务
      await configinit();
    } catch (err) {
      debugPrint("[ERROR]$err");
      // 切换到配置页面
      homelogic.tabController.index = 3;
    }
  }

  // 查看ESP设备是否可用
  static Future configinit() async {
    try {
      // 检查WebLED是否开启
      var res = await dio.get("http://$host");
      if (Config.host == res.data['IP'].toString()) {
        debugPrint("重连成功 -> ${Config.mac}");
        isOK.value = true;
        Config.mac = res.data['MAC'].toString();
        Config.color = res.data['Timecolor'].toString();
        Config.bright = res.data['Bright'];
        // 更新显示
        argssync();
        //
        saveConfig();
      }
    } catch (err) {
      debugPrint("[ERROR]$err");
      isOK.value = false;
    }
  }

  static Future configone(String uri) async {
    try {
      var res = await dio.get(uri);
      debugPrint("配置 -> ${Config.mac}");
      isOK.value = true;
      Config.host = res.data['IP'].toString();
      Config.color = res.data['Timecolor'].toString();
      Config.mac = res.data['MAC'].toString();
      Config.bright = res.data['Bright'];

      // 更新显示
      argssync();
      //
      saveConfig();
    } catch (err) {
      debugPrint("[ERROR]$err");
      isOK.value = false;
    }
  }

  // 更新显示
  static argssync() {
    configlogic.host.text = Config.host.toString();
    debugPrint("MAC:${Config.mac}");
    // 获取的颜色
    var rgb = Config.color.split(",").toList();
    powerlogic.screenPickerColor.value = Color.fromARGB(255, int.parse(rgb[0]), int.parse(rgb[1]), int.parse(rgb[2]));
    // 获取的亮度
    powerlogic.brightness.value = Config.bright.toDouble();
  }
}
